import React from 'react'
import {Form, Input, Button, Select, DatePicker, message} from 'antd'
import {getCategoryList, getFilteredProductList, postFormData, updateFormData} from '../services/restData'
import moment from 'moment'

const Option = Select.Option;
const currencyMap = ['', 'dollar', 'rupee']

class PromotionCostForm extends React.Component {
  categories;
  channels;
  products;

  constructor(props) {
    super(props)

    this.categories = []
    this.products = []
    this.channels = [
      'meetsocial',
      'sojoy',
      'miqtech',
      'mobvista',
      'lendingadda',
      'firemobo',
      'himobi',
      'fbmagictt'
    ]
    this.state = {
      promotionCostData: {
        'date': null,
        'cost': null,
        'costIn': 'dollar',
        'channelId': null,
        'appCode': null,
        'productCode': null
      },
      categories: [],
      products: [],
      operation: this.props.operation,

    }
    this.handleChange = this.handleChange.bind(this);
  }

  async handleChange(prop, val) {
    if (val) {
      this.state.promotionCostData[prop] = val;
    }
    if (prop === 'appCode') {
      this.initializeProductList(val);
    }
  }

  async initializeProductList(appCode) {
    const results = await getFilteredProductList(appCode)
    this.setState({products: results.data.productCategoryList});
    const data = this.state.promotionCostData;
    data.productCode = null;
    this.setState({promotionCostData: data});
  }

  async componentDidMount() {
    this.setState({categories: this.props.categories})
    // this.setState({products: this.props.products})
    if (this.props.operation === 'update') {
      this.setState({
        promotionCostData: {
          appCode: this.props.formData.appCode,
          productCode: this.props.formData.productCode,
          date: moment(this.props.formData.date),
          cost: this.props.formData.cost,
          costIn: currencyMap[this.props.formData.costIn],
          channelId: this.props.formData.channelId,
        }
      })
      this.props.form.setFieldsValue({
        'date': moment(this.props.formData.date),
        'cost': this.props.formData.cost,
        'costIn': currencyMap[this.props.formData.costIn],
        'channelId': this.props.formData.channelId,
        'appCode': this.props.formData.appCode,
        'productCode': this.props.formData.productCode
      })
      this.initializeProductList(this.props.formData.appCode);
    } else {
      this.props.form.setFieldsValue({
        'date': null,
        'cost': null,
        'costIn': 'dollar',
        'channelId': null,
        'appCode': null,
        'productCode': null
      })
    }
  }

  checkValidation() {
    for (let key in this.state.promotionCostData) {
      if (!this.state.promotionCostData[key]) {
        message.error(`${key} field is empty, please check.`)
        return false;
      }
    }
    return true;
  }

  async submitForm() {

    if (this.props.operation === 'add') {
      if (this.checkValidation()) {
        const formData = this.state.promotionCostData;
        formData.userName = window.localStorage.getItem('userName');
        if (await postFormData(formData)) {
          this.clearForm()
          message.success('Data Saved')
        } else {
          message.error('Error in saving data')
        }
      }

    } else {
      const formData = this.state.promotionCostData;
      formData.userName = window.localStorage.getItem('userName');
      formData.id = this.props.formData.id
      if (await updateFormData(formData)) {
        this.clearForm()
        message.success('Data Updated')
      } else {
        message.error('Error in updating data')
      }
    }
  }

  clearForm() {
    this.props.form.resetFields();
    this.setState({
      promotionCostData: {
        appCode: null,
        productCode: null,
        date: null,
        cost: null,
        costIn: 'dollar',
        channelId: null,
      }
    })
    this.props.hideForm()
  }

  render() {
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 16},
    }
    const {getFieldDecorator} = this.props.form
    return (
      <Form layout='horizontal'>
        <div style={{width: 600}}>
          <Form.Item {...formItemLayout} label='Date'
          >{getFieldDecorator('date', {rules: [{required: true}], setFieldValue: this.state.promotionCostData.date})
          (
            <DatePicker dateFormat='YYYY-MM-DD' onChange={(date, dateString) => this.handleChange('date', dateString)}/>
          )
          }</Form.Item>
          <Form.Item {...formItemLayout} label='Channel'
          >{getFieldDecorator('channelId', {
            rules: [{required: true}],
            setFieldValue: this.state.promotionCostData.channelId
          })
          (
            <Select

              placeholder="Select Channel"
              onChange={(e) => this.handleChange('channelId', e)}

            >
              {
                this.channels.map((item, index) => {
                  return (
                    <Option key={index} value={item}>{item}</Option>
                  );
                })
              }
            </Select>
          )
          }</Form.Item>
          <Form.Item {...formItemLayout} label='App Code'
          >{getFieldDecorator('appCode', {
            rules: [{required: true}],
            setFieldValue: this.state.promotionCostData.appCode
          })
          (
            <Select
              addonBefore='App'
              placeholder="Select App Code"
              onChange={(e) => this.handleChange('appCode', e)}
            >
              {
                this.state.categories.map((item, index) => {
                  return (
                    <Option key={index} value={item.appCode}>{item.appName}</Option>
                  );
                })
              }
            </Select>
          )
          }</Form.Item>
          <Form.Item {...formItemLayout} label='Product Code'
          >{getFieldDecorator('productCode', {
            rules: [{required: true}],
            setFieldValue: this.state.promotionCostData.productCode
          })
          (
            <Select
              addonBefore='Product'
              placeholder="Select Product Code"
              onChange={(e) => this.handleChange('productCode', e)}
            >
              {
                this.state.products.map((item, index) => {
                  return (
                    <Option key={index} value={item.code}>{item.name}</Option>
                  );
                })
              }
            </Select>
          )
          }</Form.Item>
          <Form.Item {...formItemLayout} label='Cost'
          >{getFieldDecorator('cost', {rules: [{required: true}], setFieldValue: this.state.promotionCostData.cost})
          (
            <Input type='number' placeholder='Enter Amount' addonBefore={
              <Select defaultValue='dollar' style={{width: 40}} onChange={(e) => this.handleChange('costIn', e)}>
                <Option value="dollar">$</Option>
                <Option value="rupee">₹</Option>
              </Select>
            } min='0' onBlur={(e) => this.handleChange('cost', e.target.value)}/>
          )
          }</Form.Item>


          <div style={{textAlign: 'center', overflow: 'hidden'}}>
            <Button style={{marginTop: '10px'}} type='primary' size='large' onClick={(e) => this.submitForm()}
            >Save</Button>
          </div>
        </div>
      </Form>
    )
  }
}

PromotionCostForm = Form.create()(PromotionCostForm)
export default PromotionCostForm
